#!/bin/bash
#
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#

function dkcl(){
        CONTAINER_IDS=$(docker ps -aq)
	echo
        if [ -z "$CONTAINER_IDS" -o "$CONTAINER_IDS" = " " ]; then
                echo "========== No containers available for deletion =========="
        else
                docker rm -f $CONTAINER_IDS
        fi
	echo
}

function dkrm(){
        DOCKER_IMAGE_IDS=$(docker images | grep "dev\|none\|test-vp\|peer[0-9]-" | awk '{print $3}')
	echo
        if [ -z "$DOCKER_IMAGE_IDS" -o "$DOCKER_IMAGE_IDS" = " " ]; then
		echo "========== No images available for deletion ==========="
        else
                docker rmi -f $DOCKER_IMAGE_IDS
        fi
	echo
}

function restartNetwork() {
	echo

        #teardown the network and clean the containers and intermediate images
	cd artifacts
	docker-compose down
	dkcl
	dkrm

	#Cleanup the material
	rm -rf /tmp/hfc-test-kvs_peerOrg* $HOME/.hfc-key-store/ /tmp/fabric-client-kvs_peerOrg*

	#Start the network
	docker-compose up -d
	cd -
	echo
}

function installNodeModules() {
	echo
	if [ -d node_modules ]; then
		echo "============== node modules installed already ============="
	else
		echo "============== Installing node modules ============="
		npm install
	fi
	echo
}

source /etc/profile
# set -x

function get_pid_by_listened_port() {
  [[ $# -lt 1  ]] && { echo 'param error: must have one param(port)'; return -1;  }
  [[ $# -gt 1  ]] && { echo 'param error: only support one param(port)'; return -1;  }

  pattern_str="*:$1\\b"
  pid=$(ss -n -t -l -p | grep "$pattern_str" | column -t | awk -F ',' '{print $(NF-1)}')

  [[ $pid =~ "pid" ]] && pid=$(echo $pid | awk -F '=' '{print $NF}')

  echo $pid
}

function kill_pid_by_listened_port() {
  pid=$(get_pid_by_listened_port $1)

  [[ -n "$pid" ]] && { echo "find pid: $pid, kill it..."; kill $pid; }
  [[ -n "$pid" ]] || { echo "not found listened port: $1"; }
}

kill_pid_by_listened_port 3389

cd ouyeelSdk
restartNetwork
installNodeModules

forever stop app.js
PORT=4000 
sleep 3
forever start app.js

sleep 10

/bin/bash init.sh

cd ..

cd ouyeelProject

installNodeModules
rm -rf  $PWD/db
sleep 5
docker run --name mongo -p 27017:27017 -v $PWD/db:/data/db -d mongo:3.2
sleep 5
nohup npm start &

cd ..
sleep 8
cd fabric-explorer

forever stop main.js

sleep 2

docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -d -v $PWD/db/:/docker-entrypoint-initdb.d/  mysql:5.6.35

sleep 10

forever start main.js
